package common.tree;

import entity.Function;

import java.util.*;

/**
 * Created by asus on 2017/6/17.
 */
public class Tree {
    private List<Node> nodes = new ArrayList<>();

    private Node root = null;//根节点

    public Tree(List<Function> functionsList) {
        for (Function function : functionsList) {
            Node node = new Node(function.getId(), function.getParentId(), function.getName(), "open", function.getSeriaNum()
                    , new NodeAttribute(function.getId(), null == function.getUrl() ? "" : function.getUrl()));
            //System.out.println("Tree:"+node);
            nodes.add(node);
            if (node.getParentId() == -1)
                root = node;
        }
        // System.out.println("Tree:size-->"+nodes.size());
        //System.out.println("RootNode:"+root);
    }

    public List<Node> build() {
        buildTree(root);
        List<Node> results = new ArrayList<Node>();
        results.add(root);
        return results;
    }

    private void buildTree(Node parent) {
        Node node = null;
        Iterator<Node> it = nodes.iterator();
        while (it.hasNext()) {
            node = it.next();
            if (Objects.equals(node.getParentId(), parent.getId())) {
                parent.getChildren().add(node);
                buildTree(node);
            }
        }
    }

    @Override
    public String toString() {
        return "Tree{" +
                "nodes=" + nodes +
                ", root=" + root +
                '}';
    }
}
